package io.zcoder.innoway.activities;


import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.zcoder.innoway.R;
import io.zcoder.innoway.utils.Utils;
import io.zcoder.innoway.adapters.ViewPagerTrendAdapter;
import io.zcoder.innoway.commons.Constants;
import io.zcoder.innoway.commons.PrefUtils;
import io.zcoder.innoway.fragments.DashboardFragment;
import io.zcoder.innoway.fragments.GoalFragment;
import io.zcoder.innoway.fragments.InfoFragment;
import io.zcoder.innoway.fragments.MeFragment;
import io.zcoder.innoway.fragments.TrendFragment;
import io.zcoder.innoway.models.Profile;
import io.zcoder.innoway.models.ProfileDetailResponse;
import io.zcoder.innoway.rest.RestClient;
import io.zcoder.innoway.widgets.TextViewCustom;
import me.relex.circleindicator.CircleIndicator;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class TopActivity extends BaseActivity implements ViewPager.OnPageChangeListener {
    public static final int REQUEST_INDEX_ENTRY = 79;

    @BindViews({R.id.img_tab_1, R.id.img_tab_2, R.id.img_tab_3, R.id.img_tab_4, R.id.img_tab_5})
    ImageView[] mImageTabs;
    @BindViews({R.id.text_tab_1, R.id.text_tab_2, R.id.text_tab_3, R.id.text_tab_4, R.id.text_tab_5})
    TextViewCustom[] mTextTabs;
    @BindView(R.id.layout_trend)
    LinearLayout mLayoutTrend;

    //Trend Layout
    @BindView(R.id.viewPager)
    ViewPager mViewPager;
    @BindView(R.id.indicator)
    CircleIndicator mIndicator;
    @BindView(R.id.common_history)
    ImageView mCommonHistory;
    @BindView(R.id.common_trend_list)
    ImageView mCommonTrendList;

    @OnClick(R.id.common_trend_list)
    void openTrendList() {
        Intent intent = new Intent(this, TrendListActivity.class);
        startActivityForResult(intent, REQUEST_INDEX_ENTRY);
    }

    @OnClick(R.id.common_history)
    void openHistory() {
        if (mProfile == null) {
            return;
        }
        Intent intent = new Intent(this, TrendHistoryActivity.class);
        intent.putExtra(Constants.INDEX_EXTRAS, mViewPager.getCurrentItem());
        intent.putExtra(Constants.UNIT_EXTRAS, mProfile.getWeight_unit());
        startActivity(intent);
    }

    private GoalFragment mGoalFragment;
    private DashboardFragment mDashboardFragment;
    private InfoFragment mInfoFragment;
    private MeFragment mMeFragment;

    private ViewPagerTrendAdapter mAdapter;
    private Profile mProfile;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_top_activity);
        ButterKnife.bind(this);
        mTextTabs[2].setTextColor(getResources().getColor(R.color.bg_select_tall_btn));
        setTitle(getString(R.string.trend_weight));
        testProfile();
        initView();
    }

    private void setTrendTab(Profile profile) {
        mCommonTrendList.setVisibility(View.VISIBLE);
        mCommonHistory.setVisibility(View.VISIBLE);

        if (mAdapter == null) {
            mAdapter = new ViewPagerTrendAdapter(null, getSupportFragmentManager(), profile);
            mViewPager.setAdapter(mAdapter);
        } else {
            mAdapter.updateProfile(profile);
            mAdapter.updateFragments();
        }
        mIndicator.setViewPager(mViewPager);
        mViewPager.setOnPageChangeListener(this);
        mViewPager.setOffscreenPageLimit(10);
    }

    public void clickTab(View view) {
        switch (view.getId()) {
            case R.id.layout_tab_1:
                setTabSelection(0);
                break;
            case R.id.layout_tab_2:
                setTabSelection(1);
                break;
            case R.id.layout_tab_3:
                setTabSelection(2);
                break;
            case R.id.layout_tab_4:
                setTabSelection(3);
                break;
            case R.id.layout_tab_5:
                setTabSelection(4);
                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        setTitle(getString(R.string.trend_) + " " + getString(Utils.getIdEntry(position)));
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private void getProfile() {
        RestClient.build(this, true).getProfile(PrefUtils.getInt(this, PrefUtils.PREF_PROFILE_ID), new Callback<ProfileDetailResponse>() {
            @Override
            public void success(ProfileDetailResponse profileDetailResponse, Response response) {
                if (profileDetailResponse.getStatus_code() != 200) {
                    showAlert(getString(R.string.error), profileDetailResponse.getMessage());
                } else {
                    mProfile = profileDetailResponse.getData();
                    if (mProfile.getBirthday() == null) {
                        Intent intent = new Intent(TopActivity.this, AddProfileActivity.class);
                        intent.putExtra(AddProfileActivity.EXTRA_PROFILE_ID, mProfile.getId());
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    } else {
                        setTrendTab(mProfile);
                    }

                }
            }

            @Override
            public void failure(RetrofitError error) {
            }
        });
    }

    private void testProfile() {
        RestClient.build(this, true).getProfile(PrefUtils.getInt(this, PrefUtils.PREF_PROFILE_ID), new Callback<ProfileDetailResponse>() {
            @Override
            public void success(ProfileDetailResponse profileDetailResponse, Response response) {
                if (profileDetailResponse.getStatus_code() != 200) {
                    showAlert(getString(R.string.error), profileDetailResponse.getMessage());
                } else {
                    mProfile = profileDetailResponse.getData();
                    if (mProfile.getBirthday() == null) {
                        Intent intent = new Intent(TopActivity.this, AddProfileActivity.class);
                        intent.putExtra(AddProfileActivity.EXTRA_PROFILE_ID, mProfile.getId());
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_INDEX_ENTRY && resultCode == TrendListActivity.RESULT_INDEX_ENTRY) {
            int index = data.getIntExtra(Constants.INDEX_EXTRAS, 0);
            mViewPager.setCurrentItem(index);
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    //init fragment
    private void initView() {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        mGoalFragment = new GoalFragment();
        transaction.add(R.id.contentLayout, mGoalFragment);

        mDashboardFragment = new DashboardFragment();
        transaction.add(R.id.contentLayout, mDashboardFragment);

        mInfoFragment = new InfoFragment();
        transaction.add(R.id.contentLayout, mInfoFragment);

        mMeFragment = new MeFragment();
        transaction.add(R.id.contentLayout, mMeFragment);

        transaction.addToBackStack(null);
        transaction.commit();

        setTabSelection(2);
    }

    private void hideFragments(FragmentTransaction transaction,
                               Fragment exceptFragment) {
        if (mGoalFragment != null) {
            if (exceptFragment == mGoalFragment)
                transaction.show(mGoalFragment);
            else
                transaction.hide(mGoalFragment);
        }
        if (mDashboardFragment != null) {
            if (exceptFragment == mDashboardFragment)
                transaction.show(mDashboardFragment);
            else
                transaction.hide(mDashboardFragment);
        }
        if (mInfoFragment != null) {
            if (exceptFragment == mInfoFragment)
                transaction.show(mInfoFragment);
            else
                transaction.hide(mInfoFragment);
        }
        if (mMeFragment != null) {
            if (exceptFragment == mMeFragment)
                transaction.show(mMeFragment);
            else
                transaction.hide(mMeFragment);
        }
    }

    
    private void setTabSelection(int index) {
        for (int i = 0; i < mTextTabs.length; i++) {
            if (i == index) {
                mTextTabs[i].setTextColor(getResources().getColor(R.color.bg_select_tall_btn));
            } else {
                mTextTabs[i].setTextColor(getResources().getColor(R.color.text_color_tabs));
            }
        }
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        switch (index) {
            case 0:
                if(findViewById(R.id.contentLayout).getVisibility() == View.GONE)
                {
                    mLayoutTrend.setVisibility(View.GONE);
                    findViewById(R.id.contentLayout).setVisibility(View.VISIBLE);
                }
                hideFragments(transaction, mGoalFragment);
                break;
            case 1:
                mLayoutTrend.setVisibility(View.VISIBLE);
                findViewById(R.id.contentLayout).setVisibility(View.GONE);
                getProfile();
                break;
            case 2:
                if(findViewById(R.id.contentLayout).getVisibility() == View.GONE)
                {
                    mLayoutTrend.setVisibility(View.GONE);
                    findViewById(R.id.contentLayout).setVisibility(View.VISIBLE);
                }
                hideFragments(transaction, mDashboardFragment);
                break;
            case 3:
                if(findViewById(R.id.contentLayout).getVisibility() == View.GONE)
                {
                    mLayoutTrend.setVisibility(View.GONE);
                    findViewById(R.id.contentLayout).setVisibility(View.VISIBLE);
                }
                hideFragments(transaction, mInfoFragment);
                break;
            case 4:
                if(findViewById(R.id.contentLayout).getVisibility() == View.GONE)
                {
                    mLayoutTrend.setVisibility(View.GONE);
                    findViewById(R.id.contentLayout).setVisibility(View.VISIBLE);
                }
                hideFragments(transaction, mMeFragment);
                break;
            default:
                hideFragments(transaction, mMeFragment);
                break;
        }
        transaction.commit();
    }
}
